#ifndef FILEPROCESSWORKER_H
#define FILEPROCESSWORKER_H

#include <QRunnable>
#include <QObject>
#include <QMutex>
#include <QString>
#include <QStringList>
#include <QDateTime>
#include "unifiedfileinfo.h"
#include "imageprocessor.h"

class QImageReader;

// 文件处理工作线程
class FileProcessWorker : public QObject, public QRunnable
{
    Q_OBJECT

public:
    explicit FileProcessWorker(int fileIndex, const QString& filePath,
                              const DpiConfiguration& dpiConfig = DpiConfiguration(),
                              QObject* parent = nullptr);
    ~FileProcessWorker();

    void run() override;
    
    // === 关键补充：任务取消接口 ===
    void cancel();
    bool isCancelled() const;

signals:
    void progressUpdated(int fileIndex, const UnifiedFileInfo& info);
    void processingFinished(int fileIndex, bool success);
    void metadataReady(int fileIndex, const QString& fileIdentity, int pageCount, const QDateTime& latestTime);

private:
    bool processPDFFile(const QString& filePath, UnifiedFileInfo& info);
    bool processImageFile(const QString& filePath, UnifiedFileInfo& info);
    void updateProgress(UnifiedFileInfo& info, int progress, const QString& statusText);
    QString getFileType(const QString& filePath);
    
    // 智能图片切割相关方法
    QColor detectBackgroundColor(const QImage& image);
    bool isEmptyRow(const QImage& image, int y, const QColor& bgColor, int threshold = 30);
    int findBestSplitPosition(const QImage& image, int startY, int targetHeight, const QColor& bgColor);
    QList<int> calculateSplitPositions(const QImage& image);
    QImage createPaddedSlice(const QImage& source, int targetHeight, const QColor& bgColor);
    
    // 流式读取时的智能分割辅助
    int findBestSplitPositionStreaming(QImageReader& reader,
                                       int startY,
                                       int targetHeight,
                                       const QSize& imageSize,
                                       const QColor& bgColor);
    
    // 占位符检测
    bool detectPlaceholderPattern(const QImage& image, int centerX, int centerY) const;

    // Martin Fowler重构：DPI配置辅助方法
    QSize getCurrentA4Size() const { return m_dpiConfig.calculateA4Size(); }
    int calculateA4TargetHeight(int imageWidth) const;

private:
    int m_fileIndex;
    QString m_filePath;
    UnifiedFileInfo m_fileInfo;
    QMutex m_mutex;
    bool m_cancelled;

    // Martin Fowler重构：DPI配置依赖注入
    DpiConfiguration m_dpiConfig;
};

#endif // FILEPROCESSWORKER_H
